﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Social.Twitter;
using Social.Facebook;
using log4net;

namespace Logic.BusinessLogic
{
	public class PostTracker
	{
		public BO.Account Account { get; set; }		
		TwitterAPI twApi;
		ITwitterConfig twConfig;
		ILog logger = LogManager.GetLogger("PostTracker");

		public PostTracker(BO.Account account, ITwitterConfig twConfig)
		{
			this.Account = account;
			this.twConfig = twConfig;
			twApi = new TwitterAPI(twConfig);
		}

		public void UpdatePoststStats()
		{
			if (Account.Posts == null || Account.Posts.Count == 0)
				return;

			twConfig.AccessToken = Account.TwToken;
			twConfig.AccessTokenSecret = Account.TwSecret;
			foreach (var post in Account.Posts)
			{
				var stat = Stats.GetTodaysPostStat(post.ID);
				GetComments(post, stat);
				stat.Update();
				post.UpdateWithNewValues(stat);
			}

		}

		private void GetComments(BO.Post post, BO.PostStat stat)
		{
			if (!string.IsNullOrEmpty(post.FbItemID))
				GetFbStats(post.FbItemID, stat);
			if (!string.IsNullOrEmpty(post.TwStatusId))
				GetTwStats(post, stat);
		}

		private void GetTwStats(BO.Post post, BO.PostStat stat)
		{
			var result = twApi.GetRepliesForStatus(post.TwStatusId, null);
			if (result.ResultOption == Social.ServiceResultOptions.Success)
			{
				stat.TwReplyNum = result.Content.Count;
			}

			var twStatus = twApi.GetRetweetCount(post.TwStatusId);
			if (twStatus.ResultOption == Social.ServiceResultOptions.Success)
				stat.TwRetweetNum = twStatus.Content;
		}

		private void GetFbStats(string fbID, BO.PostStat stat)
		{			
			var fbPost = GraphApi.GetPost(fbID);
			if (fbPost.ResultOption == Social.ServiceResultOptions.Success)
			{
				stat.FbLikeNum = fbPost.Content.likes;
				stat.FbCommentNum = fbPost.Content.comments.data.Count;
			}
			else logger.ErrorFormat("canot get FB comments for postID {0}. message:", fbID.ToString(), fbPost.Message); 
		}
	}
}
